//
//  KZBasePopView.swift
//  Fanrengame
//
//  Created by 朱凯 on 2018/4/23.
//  Copyright © 2018年 JooKey. All rights reserved.
//

import UIKit

// MARK: ------ 弹框基类
class KZBasePopView: UIControl {
    
    var contentView = UIView()
    var isHideWhenTouchShowad: Bool = true

    convenience init() {
        
        self.init(frame: .zero)
    
        setupUI()
    }
    
    deinit {
        print("销毁")
    }
 
    func setupUI() {
        
        let contentView = UIImageView()
        contentView.image = UIImage.init(named: "背景图")
        self.addSubview(contentView)
        contentView.snp.makeConstraints { (make) in
            make.width.equalTo(self).multipliedBy(0.8)
            make.center.equalTo(self)
        }
        
        let maskView = UIView()
        maskView.backgroundColor = UIColor.black.withAlphaComponent(0.2)
        contentView.addSubview(maskView)
        maskView.snp.makeConstraints { (m) in
            m.edges.equalTo(contentView)
        }
        
        self.contentView = contentView
        self.contentView.layer.cornerRadius = 8
        self.contentView.layer.masksToBounds = true

    }
    
    func show() {
        
        kWindow.addSubview(self)
        self.backgroundColor = UIColor.black.withAlphaComponent(0)
        self.snp.makeConstraints { (make) in
            make.edges.equalTo(self.superview!)
        }
        
        contentView.transform = CGAffineTransform.init(translationX: -500, y: 0)
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
            self.backgroundColor = UIColor.black.withAlphaComponent(0.6)
            self.contentView.transform = CGAffineTransform.identity
        }, completion: nil)

    }
    
    func hide() {
        UIView.animate(withDuration: 0.4, animations: {
            self.backgroundColor = UIColor.black.withAlphaComponent(0)
            self.contentView.transform = CGAffineTransform.init(translationX: 500, y: 0)

        }) { (isCompletion) in
            if isCompletion {
                self.removeFromSuperview()
            }
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        if !self.isHideWhenTouchShowad {
            return
        }
        let point = touches.first!.location(in: self)
        if self.contentView.layer.hitTest(point) != nil {
            return
        }
        hide()
    }

}
